package com.houweishi.ws.service;

import com.alibaba.fastjson.JSON;
import com.houweishi.ws.po.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 消息推送Server
 */
@ServerEndpoint("/webSocket/{userId}")
@Component
public class WebSocketServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static AtomicInteger onlineNum = new AtomicInteger();

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    /**
     * 发送消息
     * @param session
     * @param message
     * @throws IOException
     */
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                LOGGER.info("发送数据：" + message);
                session.getBasicRemote().sendText(message);
            }
        }
    }

    /**
     * 给指定用户发送信息
     * @param userId
     * @param message
     */
    public void sendInfo(String userId, String message){
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            LOGGER.error("给指定用户发送信息失败",e);
        }
    }

    /**
     * 群发消息
     * @param message
     */
    public void broadcast(String message){
    	for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                LOGGER.error("群发消息失败",e);
                continue;
            }
        }
    }

    /**
     * 建立连接成功调用
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId){
        sessionPools.put(userId, session);
        addOnlineCount();
        System.out.println(userId + "加入webSocket！当前人数为" + onlineNum);
        // 广播上线消息
        // Message msg = new Message();
        // msg.setDate(new Date());
        // msg.setFromId(Long.parseLong(userId));
        // broadcast(JSON.toJSONString(msg,true));
    }

    /**
     * 关闭连接时调用
     * @param userId
     */
    @OnClose
    public void onClose(@PathParam(value = "userId") String userId){
        sessionPools.remove(userId);
        subOnlineCount();
        LOGGER.info(userId+"断开webSocket连接！当前人数为" + onlineNum);
        // 广播下线消息
        // Message msg = new Message();
        // msg.setDate(new Date());
        // msg.setTo("-2");
        // msg.setText(userName);
        // broadcast(JSON.toJSONString(msg,true));
    }

    /**
     * 收到客户端信息后，根据接收人的username把消息推下去或者群发 to=-1群发消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message){
        LOGGER.info("server get" + message);
        Message msg=JSON.parseObject(message, Message.class);
		msg.setDate(new Date());
		if ("-1".equals(String.valueOf(msg.getNextNodeId()))) {
			// broadcast(JSON.toJSONString(msg,true));
		} else {
			sendInfo(String.valueOf(msg.getNextNodeId()), JSON.toJSONString(msg,true));
		}
    }

    /**
     * 错误时调用
     * @param session
     * @param throwable
     */
    @OnError
    public void onError(Session session, Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
    
    public static AtomicInteger getOnlineNumber() {
        return onlineNum;
    }
    
    public static ConcurrentHashMap<String, Session> getSessionPools() {
        return sessionPools;
    }
}
